<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="btnController">
        <el-button class="buttons" icon="el-icon-edit" @click="handleCreate">
          添加
        </el-button>
      </div>
      <div class="formContainer">
        <label class="filterLabel">关键词:</label>
        <el-input v-model="listQuery.keyword" placeholder="请输入关键词" class="filterInput" @keyup.enter.native="handleFilter" />
        <el-button class="buttons" @click="handleFilter">
          搜索
        </el-button>
      </div>
    </div>
    <el-table
      :key="tableKey"
      :data="list"
      style="width: 100%;"
      :header-cell-style="{background:'#ebebeb',height:'#54px'}"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="{row}">
          <span>{{ row.status_text }}</span>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createtime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template v-if="row.id!=1" slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-popconfirm
            confirm-button-text="好的"
            cancel-button-text="不用了"
            icon="el-icon-info"
            icon-color="red"
            title="删除后不可以恢复，确定删除吗？"
            @onConfirm="handleDelete(row,$index)"
          >
            <el-button slot="reference" size="mini" type="danger">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <!-- 编辑、 添加弹框表单 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="rows" label-position="right" label-width="90px" style="width: 400px; margin-left:50px;">
        <el-form-item label="上级" prop="pid">
          <el-select v-model="rows.pid" class="filter-item" placeholder="请选择">
            <el-option v-for="(item,index ) in groupOption" :key="index" :label="item" :value="parseInt(index)" v-html="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="rows.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="角色名称" prop="role_name">
          <el-input v-model="rows.role_name" :disabled="dialogStatus==='create'?false:true" placeholder="请输入角色名称" />
          <span style="color: #c0c4cc;">仅允许输入字母+数组</span>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="rows.status">
            <el-radio label="normal">正常</el-radio>
            <el-radio label="hidden">冻结</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="*权限">
          <el-tree
            v-model="rows.rulse"
            :data="roleTrees"
            show-checkbox
            node-key="id"
            :default-expand-all="expandAll"
            :default-checked-keys="rows.rules"
            :props="defaultProps"
            @check="treeCheck"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>
    <!--  -->
    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, add, edit, del, rows, roletree, groupOptions } from '@/api/managerRole'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'AttachmentIndex',
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        normal: '正常',
        hidden: '隐藏'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      expandAll: false,
      checkedKeys: [],
      roleTrees: [{
        id: 1,
        label: '一级 1',
        children: [{
          id: 4,
          label: '二级 1-1',
          children: [{
            id: 9,
            label: '三级 1-1-1'
          }, {
            id: 10,
            label: '三级 1-1-2'
          }]
        }]
      }],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      roledata: { id: '', pid: 1 },
      iconsShow: false,
      tableKey: 0,
      list: null,
      total: 0,
      listQuery: {
        page: 1,
        limit: 15,
        status: null,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      importanceOptions: [1, 2, 3],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: { 'normal': '正常', 'hidden': '冻结' },
      showReviewer: false,
      rows: {
        id: '',
        pid: 1,
        name: '',
        rules: '',
        status: 'normal',
        role_name: null
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '更新',
        create: '添加'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        pid: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        role_name: [{ required: true, message: '名称不能为空', trigger: 'blur' }]
      },
      downloadLoading: false,
      groupOption: {}

    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取列表数据
    getList() {
      var that = this
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.data
        this.total = response.data.total
        // Just to simulate the time of the request
        setTimeout(() => {
          that.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetRows() {
      this.rows = {
        ids: 0,
        pid: 1,
        title: '',
        name: '',
        url: '',
        ismenu: 1,
        status: 'normal',
        remark: '',
        role_name: null
      }
    },
    handleCreate() {
      this.resetRows()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.roletree()
      this.getGroups()
    },
    // 新增提交方法
    createData() {
      const that = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          add(that.rows).then(response => {
            that.list.unshift(this.temp)
            that.dialogFormVisible = false
            that.getList()
            that.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 编辑数据
    handleUpdate(row) {
      const that = this
      this.roledata.id = row.id
      this.roletree()
      this.getGroups()
      rows(row.id).then(function(res) {
        that.rows = Object.assign({}, res.data) // copy obj
        that.rows.ids = row.id
      })
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      const that = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.rows)
          edit(tempData.id,
            tempData.pid,
            tempData.name,
            tempData.status,
            tempData.rules).then((res) => {
            const index = that.list.findIndex(v => v.id === that.rows.ids)
            that.list.splice(index, 1, that.rows)
            that.dialogFormVisible = false
            that.$notify({
              title: 'Success',
              message: res.msg || '编辑成功',
              type: 'success',
              duration: 2000
            })
            that.getList()
          })
        }
      })
    },
    // 删除操作
    handleDelete(row, index) {
      var that = this
      del(row.id).then(res => {
        that.$notify({
          title: '操作提示',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        that.list.splice(index, 1)
      })
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    // 选择图标
    chooseIcons() {
      this.iconsShow = true
    },
    getIconval(val) {
      this.rows.icon = val
      this.iconsShow = false
    },
    // 所属上级分组
    getGroups() {
      groupOptions().then(res => {
        this.groupOption = res.data.groupdata
      })
    },
    // 角色权限分组
    roletree() {
      var that = this
      roletree(this.roledata).then(res => {
        that.roleTrees = res.data.nodelist
        that.rows.rules = res.data.check_rules
      })
    },
    // 树形结构选择事件
    treeCheck(e, options) {
      this.rows.rules = options.checkedKeys.toString()
    },
    // 展开节点
    expandBtn() {
      this.expandAll = !this.expandAll
    }

  }
}
</script>
